<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #box1{
            width: 100px;
            height: 100px;
            background: red;
            /*相对定位*/
            position: absolute;
        }
    </style>
    <script>
        window.onload = function(){
            var box1 = document.getElementById("box1");

            document.onmousemove = function(event){
                //获取鼠标坐标
                
                //1解决兼容问题
                event = event || window.event
                //获取鼠标滚动条滚动的距离

                /*
                火狐等浏览器认为滚动条为html中
                */
                var st  = document.body.scrollTop;
                var st  = document.documentElement.scrollTop;

                var sl  = document.body.scrollLeft;
                var sl  = document.documentElement.scrollLeft;
                var st  = document.body.scrollTop || document.documentElement.scrollTop;
                //获取鼠标坐标
                //clientX获取的是可视窗口的坐标
                //div的偏移量判断是相对于页面
                /*
                pageX和pageY不兼容IE8
                */
                var left = event.pageX;
                var top = event.pageY;
                //设置div偏移量
                box1.style.left = left+sl+"px";
                box1.style.top = top+st+"px";
                
            };

        };
    </script>
</head>
<body style="height: 1000px;">
    <div id="box1"></div>
</body>
</html>